﻿Module mod01
    Public _lastID As Integer = 0
    Public _zadaniPrijmyPolozky(,) As Object
    Public _zadaniVydajePolozky(,) As Object
    Public _rok As String = Date.Today.Year
    Public _mesic As String = Date.Today.Month
    Public _den As String = Date.Today.Day

    Public arrPolozky(,) As Object 'stores values for cost calculation, which are also saved in settings
    Public arrLab01(-1) As Label 'stores dynamically created lbls
    Public arrLab02(-1) As Label
    Public arrLab03(-1) As Label
    Public arrLab04(-1) As Label
    Public arrLab05(-1) As Label
    Public arrcbox01(-1) As ComboBox '--//-- cboxes
    Public arrcbox02(-1) As ComboBox
    Public arrtbox01(-1) As TextBox '--//-- tbox
    Public arrbtnRem01(-1) As Button '--//-- button (removes corresponding "row" of controls)

    Public pocKlikPlus As Long = 1 'set to 1 for 2 reasons: i. first "row" of controls ends with 00
    'ii. value is used to change location against 1st control
    Public pocKlikRemBtn As Long = 0 'set cntr for number of clicks on btnRem

    Public pocKlikPlusStr As String = ""

    'saves selected customer, if exists
    Public arrRec(-1, -1) As String
    Public arrCust(-1) As String

    Public TabulkaVydaju As DataTable
    Public TabulkaVstupy As DataTable

    '---constants
    Public Const ULOZENO As String = "Data byla úspěšně uložena!"
    Public Const NEULOZENO As String = "Data se nepodařilo uložit!"
    Public Const ZRUSENO As String = "Akce byla zrušena uživatelem!"

    'funct to handle public array for temp storage of some values
    Function Fill_zadaniPrijmyPolozky(ByVal JmenoVyrobku As String, _
                                   ByVal PocetKusu As Integer, _
                                   ByVal CenaKus As Decimal, _
                                   ByVal PoziceVpoli As Integer)
        _zadaniPrijmyPolozky(PoziceVpoli, 0) = JmenoVyrobku
        _zadaniPrijmyPolozky(PoziceVpoli, 1) = PocetKusu
        _zadaniPrijmyPolozky(PoziceVpoli, 2) = CenaKus
        Return _zadaniPrijmyPolozky
    End Function
    'funct to handle public array for temp storage of some values
    Function Fill_zadaniVydajePolozky(ByVal JmenoVyrobku As String, _
                                      ByVal PocetKusu As Integer, _
                                      ByVal CenaKus As Decimal, _
                                      ByVal PoziceVPoli As Integer)
        _zadaniVydajePolozky(PoziceVPoli, 0) = JmenoVyrobku
        _zadaniVydajePolozky(PoziceVPoli, 1) = PocetKusu
        _zadaniVydajePolozky(PoziceVPoli, 2) = CenaKus
        Return _zadaniVydajePolozky
    End Function

    'sub to hanlde filling of cbox CenaKus in "fKalkNaklForm.vb" form
    Public Sub Fill_NaklKalk_cboxCenaKus(ByVal TabulkaVydaju As Data.DataTable, _
                                   ByVal cboxCenaKus As ComboBox, _
                                   ByVal cboxVstupNazev As ComboBox)
        Dim pocRadku As Long = TabulkaVydaju.Rows.Count()
        cboxCenaKus.Items.Clear()
        For i As Long = 0 To pocRadku - 1
            If TabulkaVydaju.Rows.Item(i).Item(4) = cboxVstupNazev.SelectedValue Then
                cboxCenaKus.Items.Add(TabulkaVydaju.Rows.Item(i).Item(10).ToString)
            End If
        Next i

        If cboxCenaKus.Items.Count() > 0 Then
            cboxCenaKus.SelectedItem = cboxCenaKus.Items(0)
            If cboxCenaKus.Items.Count > 1 Then
                cboxCenaKus.DroppedDown = True
            End If
        End If
    End Sub
    'sub to handle filling of cboxes for unit price "Cena/Kus", which were generated dynamically
    Sub arrcbox01_SelectedIndexChanged(sender As ComboBox, e As EventArgs)
        TabulkaVstupy = My.Forms.fKalkNaklForm.DtbDataSet.seznam_vstupy
        TabulkaVydaju = My.Forms.fKalkNaklForm.DtbDataSet.tab_vydaj

        Dim pocRadVstupy = TabulkaVstupy.Rows.Count()
        Dim pocRadVydaju = TabulkaVydaju.Rows.Count()
        '---get number at the end of the control name
        Dim name As String = sender.Name
        Dim index As Long
        Dim fill As String = ""

        For i As Long = name.Length - 1 To 0 Step -1
            Dim ch As String = name.Substring(i, 1) 'get one char
            If Int64.TryParse(ch, index) = False Then 'if check for number fails, then
                index = Convert.ToInt64(fill) 'number was extracted, exit loop
                Exit For
            Else
                fill = ch & fill 'add char to string and get another char
            End If
        Next i

        arrcbox02(index - 1).Items.Clear() 'if sub was used before, it's necessary to clear cbox before getting new values

        For i As Long = 0 To pocRadVstupy - 1 'for all records in table "seznam_vstupy"
            If sender.SelectedItem = TabulkaVstupy.Rows.Item(i).Item(1) Then 'if selected item = item from "seznam_vstupy" row
                For ii As Long = 0 To pocRadVydaju - 1 'check this item for occurence in all records of table "tab_vydaje"
                    If TabulkaVydaju.Rows.Item(ii).Item(4) = _
                        TabulkaVstupy.Rows.Item(i).Item(0) Then
                        arrcbox02(index - 1).Items.Add(TabulkaVydaju.Rows.Item(ii).Item(10)) 'get the unit/price and add it to cbox
                    End If
                Next ii
                Exit For 'all relevant records found, exit loop
            End If
        Next i
        If arrcbox02(index - 1).Items.Count > 0 Then 'if found at least one item
            arrcbox02(index - 1).SelectedItem = arrcbox02(index - 1).Items(0) 'show it in the selection box
            If arrcbox02(index - 1).Items.Count > 1 Then 'if more then one item was found, 
                arrcbox02(index - 1).DroppedDown = True 'then display cbox dropped to force selection
            End If
        End If
    End Sub
    'sub for tbox event "text-Changed"
    Sub arrtbox_TextChanged(sender As TextBox, e As EventArgs)
        'get number from .name of textbox array
        Dim jm As String = sender.Name
        Dim fill As String = ""
        Dim numb As Long = 0
        For i As Long = jm.Length - 1 To 0 Step -1
            Dim ch As String = jm.Substring(i, 1)
            If Int64.TryParse(ch, numb) = False Then
                numb = Convert.ToInt64(fill)
                fill = ""
                Exit For
            Else
                fill = ch & fill
            End If
        Next i
        Dim index As Long = numb - 1 'get index of array where textbox is stored
        'end
        Dim mnozstvi As String = sender.Text.Trim
        Dim cenaKus As Object = arrcbox02(index).SelectedItem.ToString 'IMPORTANT! must be -2, since btnAdd00 sub runs through all code

        If sender.Text.Length > 0 Then
            If Decimal.TryParse(mnozstvi, Decimal.Zero) = True Then
                arrLab05(index).Text = _
                    Convert.ToString( _
                        Convert.ToDecimal(mnozstvi) * Convert.ToDecimal(cenaKus))
            Else
                MsgBox("Desetinné číslo nebylo zřejmě správně zadáno!", MsgBoxStyle.Critical, "Chyba!")
                Exit Sub
            End If
        End If
    End Sub
    'sub for lblPol05 event "text-changed"
    Sub arrLab05_TextChanged(sender As Label, e As EventArgs)
        'My.Forms.fKalkNaklForm.tboxCelkemShow.Text = ""
        Dim polJedna As String = My.Forms.fKalkNaklForm.lblPolNaklKusShow00.Text
        Dim CelkNakl As Decimal = 0D
        Dim celkNaklStr As String = ""


        For i As Long = 0 To arrLab05.GetUpperBound(0)
            Dim decCheck As Boolean = False
            If Decimal.TryParse(arrLab05(i).Text, Decimal.Zero) = True Then
                decCheck = True
                CelkNakl = CelkNakl + Convert.ToDecimal(arrLab05(i).Text)
            Else
                MsgBox("Desetinné číslo zřejmě nebylo správně zadáno!", MsgBoxStyle.Critical, "Chyba!")
                Exit Sub
            End If
        Next i
        celkNaklStr = Convert.ToString( _
            Convert.ToDecimal(polJedna) + CelkNakl)

        My.Forms.fKalkNaklForm.tboxCelkemShow.Text = celkNaklStr
    End Sub
    'sub for gettin sums in columns for charting
    Public Sub GetSumsForChart(ByVal tSource As DataTable _
                               , ByVal tOutput As DataTable _
                               , ByVal tSource_DateColumnName As String _
                               , ByVal tSource_CenaColumnName As String _
                               , ByVal tSource_MnozstviColumnName As String)
        Try
            Dim pocRadku As Long = tSource.Rows.Count() 'get num of rows
            Dim datumTemp As Date = tSource.Rows.Item(0).Item(tSource_DateColumnName) 'get very first date to have smthng to compare with
            Dim pocVyskytu As Long = 0 'number of occcurences (optional: strictly, it should be set to -1, since it is used to dim array
            'and also gives the real occurence number lessened by one
            Dim arrCelkPrijem(-1) As Decimal 'array for total income/expense per sold/bought item

            For i As Long = 0 To pocRadku - 1 'for all rows
                Dim tSourceRow As DataRow = tSource.Rows(i) 'get the row
                Dim tSourceDatum As Date = tSourceRow.Item(tSource_DateColumnName) 'get date
                Dim tSourceCena As Decimal = tSourceRow.Item(tSource_CenaColumnName) 'get unit price
                Dim tSourceMnozstvi As Long = tSourceRow.Item(tSource_MnozstviColumnName) 'get total number of unit's volume

                If Date.Compare(tSourceDatum, datumTemp) <> 0 Then 'if dates are not the same
                    Dim celkPrijemDen As Decimal = 0 'create total income/expense per day

                    For j As Long = 0 To arrCelkPrijem.GetUpperBound(0)
                        celkPrijemDen = celkPrijemDen + arrCelkPrijem(j) 'get total sum of all income/expenses for the day
                    Next j

                    Dim radekNovy As DataRow = tOutput.NewRow() 'create new row (will be only one, since its grouped value)
                    radekNovy(1) = datumTemp
                    radekNovy(2) = celkPrijemDen
                    tOutput.Rows.Add(radekNovy) 'add
                    tOutput.AcceptChanges() 'and save it to the table

                    pocVyskytu = 1 'reset value (must be one, since we have already new date, i.e. it's occurence value is equal to one)
                    ReDim arrCelkPrijem(pocVyskytu - 1) 'redim (and clear) array
                    arrCelkPrijem(pocVyskytu - 1) = tSourceCena * tSourceMnozstvi 'save total income per unit
                    datumTemp = tSourceDatum 'set new date to compare with

                Else
                    pocVyskytu += 1
                    ReDim Preserve arrCelkPrijem(pocVyskytu - 1)
                    arrCelkPrijem(pocVyskytu - 1) = tSourceCena * tSourceMnozstvi
                End If

            Next i
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Chyba při přípravě dat pro graf!")
            Exit Sub
        End Try
    End Sub
    'sub to fill cbox for showing stored calc (will be used onLoad and when new calc is stored)
    Public Sub FillCbox_KalkNaklShow(ByVal TableOfCalculations As DataTable _
                                     , ByVal TableOfProducts As DataTable _
                                     , ByVal CBoxToFill As ComboBox)

        Try
            CBoxToFill.Items.Clear()

            Dim vyrobky As DataTable = TableOfProducts
            Dim kalkulace As DataTable = TableOfCalculations
            Dim cbox As ComboBox = CBoxToFill
            Dim pocRadku As Long = kalkulace.Rows.Count()

            If pocRadku > 0 Then
                cbox.Enabled = True
                'cycle through calculations table
                For i As Long = 0 To pocRadku - 1
                    Dim rowKalk As DataRow = kalkulace.Rows.Item(i)
                    'cycle through products table
                    For j As Long = 0 To vyrobky.Rows.Count() - 1
                        Dim rowVyr As DataRow = vyrobky.Rows.Item(j)
                        'if ID of product in product table equals ID of product in calc. table
                        If rowVyr.Item(0) = rowKalk.Item(1) Then
                            'then check, if items is in cbox items collection
                            If cbox.Items.Count() > 0 Then
                                For k As Long = 0 To cbox.Items.Count() - 1
                                    If cbox.Items.Item(k) = rowVyr.Item(1) Then
                                        Exit For
                                    ElseIf k = cbox.Items.Count() - 1 Then
                                        cbox.Items.Add(rowVyr.Item(1))

                                    End If
                                Next k
                            Else
                                cbox.Items.Add(rowVyr.Item(1))

                            End If
                        End If
                    Next j
                Next i

            Else
                cbox.Enabled = False
            End If

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Chyba při plnění comboboxu kalkulací!")
            Exit Sub
        End Try

    End Sub
    

End Module
